package com.wumai.keystrokes.utils;

import com.wumai.keystrokes.config.Common;
import com.wumai.keystrokes.models.Position;
import com.wumai.keystrokes.models.display.Key;
import com.wumai.keystrokes.models.display.TextureResource;
import com.wumai.keystrokes.models.settings.KeyConfig;
import com.wumai.keystrokes.models.settings.KeyGroup;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.glfw.GLFW;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

public class KeyConfigManger {
    private KeyConfig keyConfig = null;
    private List<KeyGroup> keyGroups = new ArrayList<>();
    private static KeyGroup currentGroup = null;
    private static KeyConfigManger instance = null;

    public static KeyConfigManger getInstance() {
        if (instance == null) {
            instance = new KeyConfigManger();
        }
        return instance;
    }

    public static KeyGroup getCurrentGroup() {
        return currentGroup;
    }

    private void refreshConfig() {
        JsonStorage.saveConfig(keyConfig, keyGroups);
        keyConfig = JsonStorage.loadConfig();
        keyGroups = JsonStorage.loadKeyGroups();
    }

    private void generateDefaultConfig() {
        // 1.从资源目录加载默认的贴图到内存，然后保存到配置文件的资源目录中
        copyDefaultTexturesToConfigDir();
        // 2.来点默认的配置
        Key LM = new Key("LM",
                GLFW.GLFW_MOUSE_BUTTON_LEFT,
                new Position(-1.0f, -1.0f),
                0.1f, 0.1f,
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_pressed_hud.png"),
                        0, 0, 64, 64,
                        192, 192
                ),
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_released_hud.png"),
                        0, 0, 64, 64,
                        192, 192
                ),
                Key.KeyType.MOUSE
        );
        Key RM = new Key("RM",
                GLFW.GLFW_MOUSE_BUTTON_RIGHT,
                new Position(-0.8f, -1.0f),
                0.1f, 0.1f,
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_pressed_hud.png"),
                        128, 0, 64, 64,
                        192, 192
                ),
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_released_hud.png"),
                        128, 0, 64, 64,
                        192, 192
                ),
                Key.KeyType.MOUSE
        );
        Key W = new Key("W",
                GLFW.GLFW_KEY_W,
                new Position(-0.9f, -1.0f),
                0.1f, 0.1f,
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_pressed_hud.png"),
                        64, 0, 64, 64,
                        192, 192
                ),
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_released_hud.png"),
                        64, 0, 64, 64,
                        192, 192
                ),
                Key.KeyType.KEYBOARD
        );
        Key A = new Key("A",
                GLFW.GLFW_KEY_A,
                new Position(-1.0f, -0.9f),
                0.1f, 0.1f,
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_pressed_hud.png"),
                        0, 64, 64, 64,
                        192, 192
                ),
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_released_hud.png"),
                        0, 64, 64, 64,
                        192, 192
                ),
                Key.KeyType.KEYBOARD
        );
        Key S = new Key("S",
                GLFW.GLFW_KEY_S,
                new Position(-0.9f, -0.9f),
                0.1f, 0.1f,
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_pressed_hud.png"),
                        64, 64, 64, 64,
                        192, 192
                ),
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_released_hud.png"),
                        64, 64, 64, 64,
                        192, 192
                ),
                Key.KeyType.KEYBOARD
        );
        Key D = new Key("D",
                GLFW.GLFW_KEY_D,
                new Position(-0.8f, -0.9f),
                0.1f, 0.1f,
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_pressed_hud.png"),
                        128, 64, 64, 64,
                        192, 192
                ),
                new TextureResource(
                        new ResourceLocation(Common.MOD_ID, "textures/gui/default_released_hud.png"),
                        128, 64, 64, 64,
                        192, 192
                ),
                Key.KeyType.KEYBOARD
        );
        KeyGroup defaultGroup = new KeyGroup("Default", new ArrayList<Key>(6){{ add(LM); add(RM); add(W); add(A); add(S); add(D); }});
        keyGroups.add(defaultGroup);
        currentGroup = defaultGroup;
        // 3.默认的配置文件
        keyConfig = new KeyConfig("Default", "default", 0);
        // 4.刷新生效
        refreshConfig();
    }

    /**
     * 从mod资源目录复制默认纹理到配置目录
     */
    private void copyDefaultTexturesToConfigDir() {
        // 确保资源目录存在
        Path resourcesDir = JsonStorage.RESOURCES_DIR;
        if (!Files.exists(resourcesDir)) {
            try {
                Files.createDirectories(resourcesDir);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }

        // 定义默认纹理资源
        String[] defaultTextures = {
            "textures/gui/default_pressed_hud.png",
            "textures/gui/default_released_hud.png"
        };

        // 将默认纹理从mod资源复制到配置目录
        for (String texturePath : defaultTextures) {
            try {
                // 获取mod资源中的文件
                InputStream resourceStream = getClass().getClassLoader()
                    .getResourceAsStream("assets/keystrokes/" + texturePath);
                
                if (resourceStream != null) {
                    // 构造目标路径
                    Path targetPath = resourcesDir.resolve(texturePath.substring(texturePath.lastIndexOf("/") + 1));
                    
                    // 复制文件
                    Files.copy(resourceStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
                    
                    resourceStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void loadConfig() {
        keyConfig = JsonStorage.loadConfig();
        if (keyConfig == null) {
            generateDefaultConfig();
            return;
        }
        keyGroups = JsonStorage.loadKeyGroups();
        currentGroup = keyGroups.get(keyConfig.getIndex());
    }

    public void saveConfig() {
        JsonStorage.saveConfig(keyConfig, keyGroups);
    }

    public void changeCurrentConfig(int index) {
        keyConfig.setIndex(index);
        currentGroup = keyGroups.get(index);
    }

    public void addKeyGroup(String name) {
        keyGroups.add(new KeyGroup(name, new ArrayList<>()));
        refreshConfig();
    }

    public void deleteKeyGroup(int index) {
        if (index < 0 || index >= keyGroups.size()) {
            return;
        }
        keyGroups.remove(index);
        refreshConfig();
    }

    public List<KeyGroup> getKeyGroup() {
        return keyGroups;
    }

    public void removeKeyGroup(int index) {
        keyGroups.remove(index);
        refreshConfig();
    }

    public void addKeyForCurrentIndex(int index,
                                      int keyCode,
                                      String displayText,
                                      Position position,
                                      float width, float height,
                                      TextureResource pressedResource,
                                      TextureResource releasedResource,
                                      Key.KeyType keyType
    ) {
        keyGroups.get(index).getKeys().add(new Key(displayText, keyCode, position, width, height,
                pressedResource, releasedResource, keyType
        ));
        refreshConfig();
    }
}